package p.ithorns.framework.common.future;

import com.google.common.eventbus.AsyncEventBus;

import java.util.concurrent.*;

/**
 * Server
 *
 * @author ithorns
 * @version 1.0
 * @date 2021/12/11 21:16
 */
public class Server {

    ExecutorService executor = Executors.newFixedThreadPool(1);
    private final AsyncEventBus bus = new AsyncEventBus(executor);

    public <T> T sendCommand(String cmd) throws InterruptedException, ExecutionException, TimeoutException {
        SyncFuture<String> future = new SyncFuture<>();

        Command get = new Command(cmd);
        FutureHolder.put(get, future);
        bus.post(get);
        return (T) future.get(2, TimeUnit.SECONDS);
    }

    @SuppressWarnings("AlibabaAvoidManuallyCreateThread")
    public static void main(String[] args) {
        Server server = new Server();
        server.bus.register(new Device());

        Thread[] ts = new Thread[10];
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            ts[i] = new Thread(() -> {
                String o = null;
                long start = 0;
                final String cmd = "cmd" + finalI;
                try {
                    System.out.println("Server ====> 发送指令：" + cmd);
                    start = System.currentTimeMillis();
                    o = server.sendCommand(cmd);
                } catch (Exception e) {
                    System.err.println(cmd + " err: " + e.getCause());
                } finally {
                    System.out.println(cmd + ": " + o + " ========> cost: " + (System.currentTimeMillis() - start));
                }
            });
        }

        for (int i = 0; i < 10; i++) {
            ts[i].start();
        }
    }
}
